"""Command line wrapper script.

When importing Django models for the database access, an environment variable
pointing to a Django settings modules needs to be set.
For allowing that settings module to be set on the command line, this wrapper
will set the environment variable before importing the wrapped utility.

This module also contains common command line options and methods shared by
all the utilities.
"""

import os
import sys
from optparse import make_option
import logging

from django.core.management import LaxOptionParser
from django.conf import settings

common_options = (
    make_option('--settings',
        help='The Python path to a settings module, e.g. '
             '"myproject.settings.main". If this isn\'t provided, the '
             'DJANGO_SETTINGS_MODULE environment variable will be used.'),
    make_option("--debug",
        action="store_true", default=False,
        help="Debug mode"),
    make_option("-d", "--dummy",
        action="store_true", default=False,
        help="Dummy mode, does not save test results"),
    make_option("--db",
        help="Database name"),
    # XXX no such option for runner, make it importer specific.
    make_option("--unit",
        action="store_true", default=False,
        help="Run unit tests"),
    make_option("--tests-path",
        help="Location of the root directory containing the tests. "
             "Only needed if the settings file does not contain a "
             "TESTS_PATH variable."),
)

def add_common_parser_options(parser):
    parser.add_options(common_options)
    return parser

def process_options(options):
    """
    Should be called after the options have been parsed. This will do some
    settings and options post-processing common to all utilities.
    """
    logging.basicConfig(level=(logging.DEBUG if options.debug else logging.INFO))

    # tests_path can be set in the settings file instead of the command line.
    # (command line option will have precedence though).
    if not options.tests_path:
        if not hasattr(settings, "TESTS_PATH"):
            raise Exception("Missing path to the tests (no TESTS_PATH variable set "
                            "in settings nor --tests-path command line parameter)")
        options.tests_path = settings.TESTS_PATH
    options.tests_path = os.path.abspath(options.tests_path)
    assert os.path.isdir(options.tests_path), ("Directory %s does not exist" %
                                               options.tests_path)

    if options.db:
        settings.DATABASE_NAME = options.db

    # INSTALLED_APPS is required to be set when using the flush command
    if not settings.INSTALLED_APPS:
        settings.INSTALLED_APPS = ("browsertests.specs", "browsertests.tests",
                                   "browsertests.results",
                                   "browsertests.useragents")

def _handle_settings_option():
    parser = LaxOptionParser(option_list=common_options)
    options, args = parser.parse_args(sys.argv)

    if options.settings:
        os.environ['DJANGO_SETTINGS_MODULE'] = options.settings
    if not 'DJANGO_SETTINGS_MODULE' in os.environ:
        if sys.argv[1:] == ['--help']:
            parser.print_lax_help()
            print("\nIMPORTANT: to see all the options, use both --help "
                  "and --settings.\n")
            sys.exit(0)
        raise Exception("You must provide either a --settings option or set "
                        "the DJANGO_SETTINGS_MODULE environment variable")

def browsers_updtr():
    _handle_settings_option()
    from browsertests.tools import browsers_updater
    browsers_updater.main()

def tests_updtr():
    _handle_settings_option()
    from browsertests.tools import tests_updater
    tests_updater.main()

def testimporter():
    _handle_settings_option()
    from browsertests.importer import importer
    importer.main()

def testrunner():
    _handle_settings_option()
    from browsertests.runner import runner
    runner.main()

def check_regress():
    _handle_settings_option()
    from browsertests.tools import check_regress
    check_regress.main()

def bt_maintenance():
    _handle_settings_option()
    from browsertests.tools import maintenance
    maintenance.main()

# Temporary tool.
def blacklister():
    _handle_settings_option()
    from browsertests.tools import blacklister
    blacklister.main()
